<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>录入新品</title>
    <link rel="stylesheet" type="text/css" href="../css/element-plus.index.css">
    <script type="text/javascript" src="../js/vue.global.3.2.39.js"></script>
    <script type="text/javascript" src="../js/element-plus.2.2.15.js"></script>
    <script type="text/javascript" src="../js/element_plus_icons.2.0.9.js"></script>
    <script type="text/javascript" src="../js/axios.min.0.24.0.js"></script>
</head>
<body>
<div id="app">
    <el-breadcrumb separator="/">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>录入新品</el-breadcrumb-item>
    </el-breadcrumb>
    <hr>
    <el-form label-width="100px" ref="inputForm" :model="foods" :rules="formRule">
        <el-row>
            <el-col :span="12">
                <el-form-item label="鲜花名称:" prop="foodName">
                    <el-input v-model="foods.foodName" maxlength="50"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="5">
                <el-form-item label="价格:" prop="price">
                    <el-input v-model="foods.price" maxlength="10"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="描述:" prop="remarks">
                    <el-input type="textarea" rows="5" v-model="foods.remarks" maxlength="100"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="8">
                <el-form-item label="基本图片:" prop="baseImg">
                    <el-upload
                            ref="baseImageUpload"
                            v-model:file-list="baseImageList"
                            :action="fileUploadUrl"
                            :limit="1"
                            :on-exceed="handleExceedBaseImage"
                            accept=".png,.jpg,.jpeg,.gif"
                            :auto-upload="true"
                            :before-upload="handleBeforeUploadBaseImage"
                            :on-success="handleSuccessBaseImage"
                            :on-remove="handleRemoveBaseImage"
                    >
                        <template #trigger>
                            <el-button type="primary">选择文件</el-button>
                        </template>
                        <template #tip>
                            <div class="el-upload__tip">
                                只允许上传 jpg/png 文件且大小不超过 5MB.
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <img v-if="baseImageUrl" :src="baseImageUrl" alt="基本图片" style="height: 120px;">
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="8">
                <el-form-item label="详情图片:">
                    <el-upload
                            ref="detailImageUpload"
                            v-model:file-list="detailImageList"
                            :action="fileUploadUrl"
                            :on-success="handleSuccessDetailImage"
                            :on-remove="handleRemoveDetailImage"
                            :before-upload="handleBeforeUploadDetailImage"
                            :limit="8"
                            multiple
                            :on-exceed="handleExceedBaseImage"
                            accept=".png,.jpg,.jpeg,.gif"
                            :auto-upload="true"
                    >
                        <template #trigger>
                            <el-button type="primary">选择文件</el-button>
                        </template>
                        <template #tip>
                            <div class="el-upload__tip">
                                允许上传8张 jpg/png 图片且每个文件大小不超过 5MB.
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-col>
            <el-col :span="16">
                <img v-for="path in detailImageUrl" :src="path" alt="tupian" style="height: 120px;">
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="12">
                <el-form-item label="所属类别:" prop="catId">
                    <el-checkbox-group v-model="foods.catId">
                        <el-checkbox v-for="cat in allCategoryList" :label="cat.catId">{{cat.catName}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="12">
                <el-form-item label="标签:" prop="tagId">
                    <el-checkbox-group v-model="foods.tagId">
                        <el-checkbox v-for="tag in allTagList" :label="tag.tagId">{{tag.tagName}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="12">
                <el-form-item>
                    <el-button type="primary" @click="handleAddFoods">录入</el-button>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</div>
<script src="../js/common.js"></script>
<script type="text/javascript">
    const options = {
        data() {
            return {
                foods: {
                    foodName: '',
                    price: '',
                    remarks: '',
                    catId: [],
                    tagId: [],
                    //基本图片
                    baseImg: '',
                    //详情图片
                    imgPath: []
                },
                baseImageList: [],
                detailImageList: [],
                fileUploadUrl: SERVER_BASE_URL + "/upload",
                allTagList: [],
                allCategoryList: [],
                baseImageUrl: '',
                detailImageUrl: [],
                formRule:{
                    foodName:[
                        {required:true,message:'请输入菜品名称!',trigger:'blur'}
                    ],
                    price:[
                        {required:true,message:'请输入菜品价格!',trigger:'blur'},
                        {validator:this.checkNumber,message:'请输入有效数值!',trigger:'blur'}
                    ],
                    baseImg:[
                        {required:true,message:'请上传基本图片!'}
                    ],
                    catId:[
                        {required:true,message:'请选择菜品分类!'},
                        {validator:this.checkArrayLength,message:'请至少选择一个所属分类!',trigger:'blur'}
                    ]
                }
            };
        },
        methods: {
            checkNumber(rule,value,callback){
                let r=Number(value);
                if(isNaN(r)){
                    return false;
                }
                return true;
            },
            checkArrayLength(rule,value,callback){
                if(value.length==0)return false;
                return true;
            },
            handleBeforeUploadBaseImage(file) {
                if (!file.type.startsWith("image/")) {
                    ElementPlus.ElMessage({
                        type: 'error',
                        message: '只能上传图片文件!'
                    });
                    return false;
                }
                if (file.size >= 5 * 1024 * 1024) {
                    ElementPlus.ElMessage({
                        type: 'error',
                        message: '文件大小必须小于5MB!'
                    });
                    return false;
                }
                return true;
            },
            handleBeforeUploadDetailImage(file) {
                let type = file.type;
                let regexp = /^image\/.{1,4}$/i;
                if (!regexp.test(type)) {
                    ElementPlus.ElMessage({
                        type: 'error',
                        message: '只能上传图片文件!'
                    });
                    return false;
                }
                if (file.size >= 5 * 1024 * 1024) {
                    ElementPlus.ElMessage({
                        type: 'error',
                        message: '文件大小必须小于5MB!'
                    });
                    return false;
                }
                return true;
            },
            handleExceedBaseImage(fileList, uploadFiles) {
                ElementPlus.ElMessage({
                    type: 'error',
                    message: '上传文件超过数量限制'
                });
            },
            handleSuccessBaseImage(resp) {
                this.foods.baseImg = resp;
                this.baseImageUrl = SERVER_BASE_URL + "/static/img/" + resp;
            },
            handleSuccessDetailImage(resp) {
                this.foods.imgPath.push(resp);
                this.detailImageUrl.push(SERVER_BASE_URL + "/static/img/" + resp);
            },
            handleRemoveBaseImage(file, files) {
                if (file.status == 'success') {
                    axios.get('/deleteFile', {params: {path: file.response}}).then(() => {
                    });
                }
                this.baseImageUrl = '';
                this.foods.baseImg = '';
            },
            handleRemoveDetailImage(file, files) {
                if (file.status == 'success') {
                    let subPath = file.response;
                    axios.get('/deleteFile', {params: {path: subPath}}).then(() => {
                    });
                    for (let i = 0; i < this.foods.imgPath.length; i++) {
                        if (this.foods.imgPath[i] == subPath) {
                            this.foods.imgPath.splice(i, 1);
                        }
                    }
                    this.detailImageUrl.splice(0);
                    for (let i = 0; i < this.foods.imgPath.length; i++) {
                        this.detailImageUrl.push(SERVER_BASE_URL + "/static/img/" + this.foods.imgPath[i]);
                    }
                }
            },
            handleAddFoods(){
                let _this=this;
                this.$refs['inputForm'].validate(valid=>{
                    if(valid){
                        //发送AJAX请求
                        axios.post('/foods/add',this.foods).then(resp=>{
                            //TODO 清除表单中的所有内容、基本图片和详情图片，提示录入成功

                            _this.$refs['inputForm'].resetFields();
                            _this.$refs['baseImageUpload'].clearFiles();
                            _this.$refs['detailImageUpload'].clearFiles();
                            _this.baseImageUrl='';
                            -this.detailImageUrl.splice(0);
                            ElementPlus.ElMessage({
                                type:'success',
                                message:'录入成功!'
                            });
                        });
                    }
                });
            }
        },
        created() {
            //标签列表
            axios.get('/tag/list').then(resp => {
                this.allTagList = resp;
            });
            //类别列表
            axios.get('/cat/list').then(resp => {
                this.allCategoryList = resp;
            });
        }
    };
    const app = Vue.createApp(options);
    app.use(ElementPlus);
    for (const [iconName, iconComp] of Object.entries(ElementPlusIconsVue)) {
        if (iconName == 'Menu') {
            app.component('IconMenu', iconComp);
        } else {
            app.component(iconName, iconComp);
        }
    }
    const vm = app.mount("#app");







</script>
</body>
</html>